import qs from 'qs'
// const baseUrl = 'http://sfams.win07.cn/prod-api' // 远程服务器地址
export const baseUrl = 'http://192.168.50.100:8000' // 本地服务器地址
// export const baseUrl = 'http://localhost:8000' // 本地服务器地址 192.168.50.100
const loginPage = "/pages/ucenter/login/wxLogin"
const request = (url, data, method, header = {}) => {
	const token = uni.getStorageSync('token');
	if (token) {
		header.Authorization = 'Bearer ' + token
	}
	header['Content-Type'] = 'application/json;charset=UTF-8'
	url = baseUrl + url
	if (data) {
		data = removePropertyOfNull(data)
	}
	if (data && method === 'GET') {
		data = qs.stringify(data)
		url += '?' + data
		data = {}
	}


	return new Promise((resolve, reject) => {
		uni.request({
			url, //仅为示例，并非真实接口地址。 complete
			method,
			header,
			data,
			success: (res) => {
				uni.hideLoading();
				// 返回成功
				if (res.statusCode === 200 && res.data.code === 200) {
					resolve(res.data)
					return
				}
				
				if (res.statusCode === 401 || res.statusCode === 403) {
					// uni.navigateTo({url:loginPage})
					uni.showToast({
						icon: 'none',
						title: res.data.msg || '系统异常，请稍后再试！'
					});
				} else {
					if (res.data) {
						if (res.data.code === 401) {
							//token已过期，清除登录缓存
							uni.removeStorage({
								key: 'gkms-userInfo',
								success: function(res) {
									// console.log('缓存移除userInfo成功');
								}
							});
							uni.removeStorage({
								key: 'token',
								success: function(res) {
									// console.log('缓存移除token成功');
								}
							});
						}else{
							uni.showToast({
								icon: 'none',
								title: res.data.msg || '系统异常，请稍后再试！'
							});
						}
						reject(res)
						return
					}
				}
			},
			fail(res) {
				console.log('fail响应', res);
				uni.hideLoading();
				// if(res.statusCode === 401 && res.data.code === 401) {
				// 	uni.navigateTo({url:loginPage})
				// 	return
				// }
				let msg = res.data ? res.data.msg : '系统异常，请稍后再试！'
				uni.showToast({
					icon: 'none',
					title: msg
				});
				reject(res)
				return
			}
		})
	})
}
var removePropertyOfNull = function(obj) {
	Object.keys(obj).forEach(item => {
		if (!obj[item]) delete obj[item]
	})
	return obj;
}
export default request
